//
//  HomeDetailViewController.m
//  Tang
//
//  Created by lanou on 15/12/7.
//  Copyright © 2015年 352324497@qq.com. All rights reserved.
//

#import "HomeDetailViewController.h"
#import "H_D_FirCell.h"
#import "H_D_SecCell.h"
#import "CoreDataMan.h"
#import "SKUDetailController.h"

#import "HomeDetailModel.h"
#import "PictureModel.h"
#import "UMSocial.h"
#import "WebViewController.h"

#define KPicUrl @"http://bt.img.17gwx.com/%@"

//#import "SKUDetailController.h"

#define KHDUrl @"http://open3.bantangapp.com/topic/newInfo?app_installtime=1449053241.284786&app_versions=5.0.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&id=%@"

@interface HomeDetailViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) UIImageView *headerIcon;//头图片
@property (nonatomic, strong) UILabel *titleLabel;//标题
@end



static NSString *cellForTab = @"cell3";

static NSString *cellForFir = @"cell1";//
@implementation HomeDetailViewController
{
    CGFloat headerIconHeight;
    NSString *headerDesc;
    NSString *titleName;
    
}



- (void)viewWillAppear:(BOOL)animated
{
    [self.tableView reloadData];

}
- (NSMutableArray *)modelArray
{
    if (!_modelArray)
    {
        self.modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
   // NSLog(@"%@,%@",_PinJieId,_headerImage);
    
    self.navigationController.navigationBar.translucent = YES;
    
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    
    
    headerIconHeight = KWidth * 330 / 620  ;
    
    self.tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStyleGrouped];
    [self.tableView registerClass:[H_D_FirCell class] forCellReuseIdentifier:cellForFir];
    [self.tableView registerClass:[H_D_SecCell class] forCellReuseIdentifier:cellForTab ];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.contentInset = UIEdgeInsetsMake(headerIconHeight, 0, 0, 0);
    [self.view addSubview:_tableView];
    
    
    
    
    self.headerIcon = [[UIImageView alloc] initWithImage:self.headerImage];
    self.headerIcon.frame = CGRectMake(0, - headerIconHeight  , KWidth, headerIconHeight + 40*KWidth / 375 );
    [self.tableView addSubview:_headerIcon];
    self.tableView.separatorStyle  = 0;
    
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    self.titleLabel.text = @"购物清单";
    self.titleLabel.textColor = [UIColor clearColor];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = _titleLabel;
    self.titleLabel.alpha = 0;
    
    
     UIButton *btn = (UIButton *)self.navigationItem.leftBarButtonItem.customView;
    [btn addTarget:self action:@selector(leftAtnActiion:) forControlEvents:UIControlEventTouchUpInside];
    
    [self requestWithUrl:[NSString stringWithFormat:KHDUrl,_PinJieId]];
    
    UIButton *rightBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 25, 25);
    [rightBtn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem=rightItem;
    
}

- (void)leftAtnActiion:(UIButton *)btn
{
    self.navigationController.navigationBar.translucent = NO;
}

- (void)rightBtnAction:(UIButton *)button
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5668e3bde0f55a90700038ed"
                                      shareText:@"推荐好物, 分享视频 https://itunes.apple.com/cn/app/%e7%b3%96%e5%a6%86/id1068451018?mt=8"
                                     shareImage:[UIImage imageNamed:@"Tango"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatTimeline, UMShareToWechatSession, UMShareToEmail, UMShareToSms,nil] delegate:nil];
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}


/**
 *  网络请求
 *
 *  @param url 一个字符串
 */
- (void)requestWithUrl:(NSString *)url
{
    //NSLog(@"%@",url);
    [[NetworkState shareInstance] reachablityStatesWithDongHua:self];
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
      {
          if (data == nil)
          {
              NSLog(@"请求失败");
              [[NetworkState shareInstance]finshYYToVc:self];
              UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲, 网络好像不是很给力哦~~~" preferredStyle:(UIAlertControllerStyleAlert)];
              UIAlertAction *OKaction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                  [self dismissViewControllerAnimated:YES completion:nil];
              }];
              [alertView addAction:OKaction];
              [self presentViewController:alertView animated:YES completion:nil];
              return ;
          }
          
          NSDictionary *firDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
          NSDictionary *secDic = firDic[@"data"];
          headerDesc = secDic[@"desc"];
          titleName = secDic[@"title"];
          
          for (NSDictionary * thrDic  in secDic[@"product"])
          {
              HomeDetailModel *hoModel = [[HomeDetailModel alloc] init];
              [hoModel setValuesForKeysWithDictionary:thrDic];
              hoModel.picArray = [NSMutableArray array];
              for (NSDictionary *forDic in thrDic[@"pic"])
              {
                  PictureModel *model = [[PictureModel alloc] init];
                  [model setValuesForKeysWithDictionary:forDic];
                  [hoModel.picArray addObject:model];
              }
              [self.modelArray addObject:hoModel];
          }
          
          dispatch_async(dispatch_get_main_queue(), ^
          {
              [[NetworkState shareInstance] finshYYToVc:self];
              [self.tableView reloadData];
              
          });
          
        
    }] resume];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.modelArray.count == 0)
    {
        return 0;
    }
    else
    {
        return 2;
    }
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }
    else
    {
        return _modelArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        H_D_FirCell *cell = [tableView dequeueReusableCellWithIdentifier:cellForFir forIndexPath:indexPath];
        
        [cell setTitleLabelDescrLabelWithstring:titleName descr:headerDesc];
        return cell;
    }
    else if(indexPath.section == 1)
    {
        H_D_SecCell *cell = [tableView dequeueReusableCellWithIdentifier:cellForTab forIndexPath:indexPath];
        HomeDetailModel *model = _modelArray[indexPath.row];
        [cell setModel:model num:indexPath.row];
        
        cell.comment.userInteractionEnabled = NO;
       
        
        [cell.like removeTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.like addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.like.tag = 2000+indexPath.row;
        
        [cell.shop removeTarget:self action:@selector(shopAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.shop addTarget:self action:@selector(shopAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.shop.tag = 3000 + indexPath.row;
        
    return cell;
        
   }
    else
    {
        return nil;
    }
}


#pragma mark  ---cell 上button事件 ---

//- (void)commentAction:(DIYButton *)btn
//{
//    HomeDetailModel *model = self.modelArray[btn.tag - 1000];
//}

- (void)likeAction:(DIYButton *)btn
{
    BmobUser *bUser = [BmobUser getCurrentUser];
    if (bUser)
    {

    btn.selected = !btn.selected;
    HomeDetailModel *model = self.modelArray[btn.tag - 2000];
    PictureModel *picModel = model.picArray[0];

    if (btn.selected)
    {
        
        [[CoreDataMan shareIntance] addSku:[NSString stringWithFormat:@"%ld",model.Id] imageUrl:[NSString stringWithFormat:KPicUrl,picModel.p] title:model.title type_id:nil width:picModel.w height:picModel.h];
    }
    else
    {
        [[CoreDataMan shareIntance] deleteSkuWithId:[NSString stringWithFormat:@"%ld",model.Id]];
    }
    }
    else
    {
        [CallTool alertActionWithTitle:@"提示" message:@"还没有登陆哦,请先登陆" other:@"取消"uiViewController:self];
    }
    
}

- (void)shopAction:(DIYButton *)btn
{
    HomeDetailModel *model = self.modelArray[btn.tag - 3000];
    WebViewController *webVc = [[WebViewController alloc] init];
    webVc.url = model.url;
    
    [self.navigationController pushViewController:webVc animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return [H_D_FirCell heightForRowWithTitle:titleName desc:headerDesc] + 20 *KWidth / 414;
    }
    else
    {
        HomeDetailModel *model = _modelArray[indexPath.row];
        return [H_D_SecCell heightForCellWithModel:model];
    }
    
}

#pragma mark  ----点击跳转-----
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section ==1)
    {
        HomeDetailModel *model = _modelArray[indexPath.row];
        
        
        SKUDetailController *skuVc = [[SKUDetailController alloc] init];
        skuVc.ID = [NSString stringWithFormat:@"%ld",model.Id];
        [self.navigationController pushViewController:skuVc animated:YES];
    }
    
}

#pragma mark  --返回表头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1)
    {
        
        UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    view.alpha = 1;
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake((KWidth - 100)/2,  10, 100, 30*KWidth / 414)];
    
    label.text = @"物品精选";
    label.textColor = [UIColor orangeColor];
    label.font = [UIFont systemFontOfSize:18];
    label.textAlignment = NSTextAlignmentCenter;
    
    
    [view addSubview:label];
        return view;

    }
    else
    {
        return nil;
    }
        
    
    
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0.0f;
    }
    else if(section == 1)
    {
        return 40*KWidth / 414 ;
    }
    else
    {
        return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1f;
}



#pragma  mark ---下啦放大---
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset = scrollView.contentOffset.y;
    CGFloat xOffeset = yOffset + headerIconHeight;
    // NSLog(@"yOffset ==%f, xOffeset==%f",yOffset,xOffeset);
    self.titleLabel.textColor = [UIColor clearColor];
    if (yOffset < - headerIconHeight)
    {
        CGRect rect = self.headerIcon.frame;
        rect.origin.y = yOffset;
        rect.size.height = - yOffset+40*KWidth / 375;
        rect.origin.x = xOffeset;
        rect.size.width = KWidth + fabs(xOffeset) * 2;
        self.headerIcon.frame = rect;
    }
    else
    {
        if  (yOffset <= 0)
            
        {
            CGFloat y = fabs(yOffset) ;
            self.tableView.contentInset = UIEdgeInsetsMake(y, 0, 0, 0);
            

           
        }
 
    }
    if (yOffset >= 0)
    {
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        //self.navigationController.navigationBar.translucent = NO;

    }
    
    CGFloat alpha = (yOffset + headerIconHeight) / headerIconHeight;
    if (alpha > 0.5)
    {
        UIButton *btn = (UIButton *)self.navigationItem.leftBarButtonItem.customView;
        [btn setTitleColor:[[UIColor blackColor]colorWithAlphaComponent:alpha] forState:UIControlStateNormal];
        self.titleLabel.textColor = [[UIColor blackColor]colorWithAlphaComponent:alpha];
        
    }
    else
    {
        UIButton *btn = (UIButton *)self.navigationItem.leftBarButtonItem.customView;
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        self.titleLabel.textColor = [UIColor blackColor];
    }
    
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor whiteColor] colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
    self.titleLabel.alpha = alpha;
    alpha = fabs(alpha);
    alpha = fabs(1 - alpha);
    alpha = alpha < 0.2? 0 :alpha - 0.2;
}

- (UIImage *)imageWithColor:(UIColor *)color
{
    // 描述矩形
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    //开启位图上下文
    UIGraphicsBeginImageContext(rect.size);
    
    // 获取位图上下文
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // 使用color 演示填充上下文
    CGContextSetFillColorWithColor(context, [color CGColor]);
    
    // 渲染上下文
    CGContextFillRect(context, rect);
    
    // 从上下文中获取图片
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 结束上下文
    UIGraphicsEndImageContext();
    return theImage;
    
}


@end
